package com.synjones.idcardusb_reader;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.synjones.cominterface.DeviceConnectManager;
import com.synjones.cominterface.ReaderInterface;
import com.synjones.cominterface.ReaderInterfaceFactory;
import com.synjones.cominterface.serial.SerialPortFinder;
import com.synjones.idcard.IDCard;
import com.synjones.util.LocalSharedPreferences;
import com.synjones.util.SPNameInterface;

public class MainActivity extends AppCompatActivity {

    CardInfoView cardInfoView;
    IDCardReaderThread idCardReaderThread;
    int currentCom=0;
    Button btnRead;
    Button btnExit;
    TextView tvConnectStatus;
    TextView tvReaderStatus;
    final int UPDATE_READER_STATUS=0x40;
    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String devName=DeviceConnectManager.getInstance().getDevName();
            switch (msg.what){
                case DeviceConnectManager.MESSAGE_CONNECTED:
                    tvConnectStatus.setText(devName+"连接成功");
                    break;
                case DeviceConnectManager.MESSAGE_CONNECTING_DEVICE:
                    tvConnectStatus.setText(devName+"正在连接");
                    break;
                case DeviceConnectManager.MESSAGE_CONNECTFAILED:
                    tvConnectStatus.setText(devName+"连接失败");
                    break;
                case DeviceConnectManager.MESSAGE_DISCONNECTED:
                    tvConnectStatus.setText(devName+"连接关闭");
                    break;
                case DeviceConnectManager.MESSAGE_RECONNECT_DEVICE:
                    tvConnectStatus.setText(devName+"重新连接");
                    break;
                case DeviceConnectManager.MESSAGE_STOP_READCARD:
                    break;
                case IDCardReaderThread.MESSAGE_START_READ:
                    new MyTimer().start();
                    btnRead.setText("停止");
                    break;
                case IDCardReaderThread.MESSAGE_DISPLAY_IDCARD:
                    cardInfoView.showCardView((IDCard) msg.obj);
                    break;
                case IDCardReaderThread.MESSAGE_STOP_READ:
                    btnRead.setText("读卡");
                    break;
                case UPDATE_READER_STATUS:
                    tvReaderStatus.setText(idCardReaderThread.getReadStatus());
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initViews();
        DeviceConnectManager.getInstance().resetReader(ReaderInterfaceFactory.READER_USB);
        idCardReaderThread = new IDCardReaderThread();
        idCardReaderThread.setActivityAndHandler(this,mHandler);
        idCardReaderThread.open(null);
    }


    @Override
    protected void onDestroy() {
        idCardReaderThread.close();
        super.onDestroy();
    }


    void initViews(){
        cardInfoView=new CardInfoView(this);
        btnRead=(Button)findViewById(R.id.buttonReadCard);
        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (idCardReaderThread.isReading()) {
                    idCardReaderThread.stop();
                } else {
                    idCardReaderThread.read();
                }
            }
        });

        btnExit=(Button)findViewById(R.id.buttonExit);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idCardReaderThread.close();
                finish();
            }
        });

        Button btnReadM1=(Button)findViewById(R.id.buttonM1);
        btnReadM1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idCardReaderThread.stop();
                startActivity(new Intent(MainActivity.this,ReadM1CardActivity.class));
            }
        });


        Button btnReadCpu=(Button)findViewById(R.id.buttonCpu);
        btnReadCpu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idCardReaderThread.stop();
                startActivity(new Intent(MainActivity.this,ReadCpuCardActivity.class));
            }
        });


        tvConnectStatus =(TextView)findViewById(R.id.textViewStatus);
        tvReaderStatus =(TextView)findViewById(R.id.tvReaderStatus);
        Spinner spCom = (Spinner) findViewById(R.id.spCom);
        final Spinner spSerialPort = (Spinner) findViewById(R.id.spSerialPort);
        final Spinner spSerialBaudrate = (Spinner) findViewById(R.id.spSerialBaudrate);
        assert spCom != null;
        spCom.setSelection(0, false);
        spCom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {

                if(pos==1){
                    spSerialPort.setVisibility(View.VISIBLE);
                    spSerialBaudrate.setVisibility(View.VISIBLE);
                    SerialPortFinder serialPortFinder=new SerialPortFinder();
                    final String devs[]= serialPortFinder.getAllDevicesPath();
                    ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, devs);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spSerialPort.setAdapter(adapter);
                    spSerialPort.setSelection(0,false);
                    spSerialPort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                            LocalSharedPreferences.getSp(MainActivity.this).
                                    edit().putString(SPNameInterface.SP_SERIAL_NAME,devs[pos]).commit();
                            DeviceConnectManager.getInstance().resetReader(ReaderInterfaceFactory.READER_SERIAL);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    spSerialBaudrate.setSelection(3,false);
                    spSerialBaudrate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                            String[] baudRate = getResources().getStringArray(R.array.baudRate);
                            LocalSharedPreferences.getSp(MainActivity.this).
                                    edit().putString(SPNameInterface.SP_SERIAL_BAUDRATE,baudRate[pos]).commit();
                            DeviceConnectManager.getInstance().resetReader(ReaderInterfaceFactory.READER_SERIAL);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });

                }else{
                    spSerialPort.setVisibility(View.INVISIBLE);
                    spSerialBaudrate.setVisibility(View.INVISIBLE);
                }
                currentCom=pos;
                int reader_com=currentCom==0?ReaderInterfaceFactory.READER_USB:ReaderInterfaceFactory.READER_SERIAL;
                DeviceConnectManager.getInstance().resetReader(reader_com);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

    }


    class MyTimer extends Thread{
        @Override
        public void run() {
            while(idCardReaderThread.isReading()){
                mHandler.obtainMessage(UPDATE_READER_STATUS).sendToTarget();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
